# -*- coding: UTF-8 -*-
import ttk
import time
import Queue
import threading
import Tkinter as Tk
import binascii
import serial.tools.list_ports
import sys
from datetime import datetime
import json

isOpened = threading.Event()
RQueue = Queue.Queue(maxsize=1024)
Recebuf = Queue.Queue(maxsize=1024)
send_data_len_cnt = 0
rece_data_len_cnt = 0
Rbuf = ''

crc232_flag = 0

root = Tk.Tk()
var = Tk.IntVar()
ComX = Tk.StringVar(root,"COM1")
Baud = Tk.StringVar(root,"9600")
Dbit = Tk.StringVar(root,'8')
Sbit = Tk.StringVar(root,'1')
Chck = Tk.StringVar(root,"None")
Enty = Tk.StringVar(root,"")
HexD = Tk.BooleanVar(root,False)
HexO = Tk.BooleanVar(root,False)
Open = Tk.StringVar(root,u"打开")
Radio_text = Tk.StringVar(root,"9600")
Baud_set = Tk.StringVar(root,"9600")
status = Tk.StringVar(root,u"亮")
dog_time = Tk.StringVar(root,0)
stateInfo = Tk.StringVar(root,u"1:订阅")
state = Tk.StringVar(root,"1:正常在线")
sett_mode = Tk.StringVar(root,u"1:AP")
port_list = ["COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","COM10",
             "COM11","COM12","COM13","COM14","COM15","COM16","COM17","COM18","COM19","COM20",]

time_list = [i for i in xrange(61)]

state_list = ["1:正常在线","2:wifi未连接","3:服务器未连接","4:未注册","5:AP配置状态","6:ESPTOU配置状态"]


txt0 = Tk.StringVar(root,"")
txt1 = Tk.StringVar(root,"")
txt2 = Tk.StringVar(root,"")
txt3 = Tk.StringVar(root,"")
txt4 = Tk.StringVar(root,"")
txt5 = Tk.StringVar(root,"")
txt6 = Tk.StringVar(root,"")
txt7 = Tk.StringVar(root,"")
txt_open_cnt = 0

led_status = Tk.StringVar(root,"black")
led_fun = Tk.StringVar(root,u"启用")
led_sta = 'black'
led_status_old = 'black'
led_status_read_cnt = 0
led_fun_open_flag = 0
led_retrun_again = 0

time_type = Tk.StringVar(root,u"单次")
time_id = Tk.StringVar(root,0)
time_open= Tk.StringVar(root,u"开启")
time_date = Tk.StringVar(root,u"2016-11-29T02:49:00.000Z")
time_do = Tk.StringVar(root,u"on")
time_startdo = Tk.StringVar(root,u"无")
time_enddo = Tk.StringVar(root,u"无")
time_operate = Tk.StringVar(root,u"新建")
time_id_array = Tk.StringVar(root,'')
time_sub = Tk.StringVar(root,u'订阅定时器通知')

COM = serial.Serial()
lock = threading.Lock()

def change_crc32():
    global crc232_flag

    if HexD.get():
        crc232_flag = 1
    else:
        crc232_flag = 0

def set_status(status):
    status.set("亮")

def reset_status(status):
    status.set("灭")

def Write_set_state(state, send_en):
    Write_instruct_in_close_led_fun("[\"state\"]",send_en)

def Write_set_stateInfo(stateInfo, send_en):
    global send_data_len_cnt
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    s = "[\"stateInfo\","
    state = stateInfo.get()
    if state.find("1")!= -1:
        state = '1'
    else:
        state = '0'
    s += state
    s += ']\n'

    if led_fun_open_flag!=0:
        return
    if isOpened.isSet():
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        data_len = len(s) - 1
        if data_len == 0:
            return
        head_len = COM_add_data_head(s, list)

        for i in range(head_len):
            COM.write(chr(list[i]))
        print "send head:"+str(list[0:head_len])
        fp.writelines("send content:")
        fp.writelines((str)(list[0:head_len]))
        for j in range(data_len):
            COM.write(str(s[j]))
        print "send data:"+s
        fp.writelines(s+'\n')
        fp.close()

        send_en.delete(0, 10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0, send_data_len_cnt)

def Write_set_dogtime(dog_time, send_en):
    global send_data_len_cnt
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    s = "[\"dog\","
    time = dog_time.get()
    s += time
    s += ']\n'

    if led_fun_open_flag!=0:
        return
    if isOpened.isSet():
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        data_len = len(s) - 1
        if data_len == 0:
            return
        head_len = COM_add_data_head(s, list)

        for i in range(head_len):
            COM.write(chr(list[i]))
        print "send head:"+str(list[0:head_len])
        fp.writelines("send content:")
        fp.writelines((str)(list[0:head_len]))
        for j in range(data_len):
            COM.write(str(s[j]))
        print "send data:"+s
        fp.writelines(s+'\n')
        fp.close()

        send_en.delete(0, 10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0, send_data_len_cnt)

def Write_set_status_led_instruct(status,send_en):
    global send_data_len_cnt
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    s = "[\"sled\","

    if led_fun_open_flag!=0:
        return
    if isOpened.isSet():
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        if status.get()==0:
            return
        if status.get()==1:
            s += "1]\n"
        else:
            s += "0]\n"

        data_len = len(s) - 1
        if data_len == 0:
            return
        head_len = COM_add_data_head(s, list)

        for i in range(head_len):
            COM.write(chr(list[i]))

        print "send head:"+str(list[0:head_len])
        fp.writelines("send content:")
        fp.writelines((str)(list[0:head_len]))
        for j in range(data_len):
            COM.write(str(s[j]))
        print "send data:"+s
        fp.writelines(s+'\n')
        fp.close()

        send_en.delete(0, 10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0, send_data_len_cnt)


def  Write_set_baud_instruct(Baud_set,send_en):
    global send_data_len_cnt
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    s = "[\"baudrate\","
    baud = Baud_set.get()
    s += baud
    s += ']\n'
    if led_fun_open_flag!=0:
        return
    if isOpened.isSet():
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        data_len = len(s) - 1
        if data_len == 0:
            return
        head_len = COM_add_data_head(s, list)

        for i in range(head_len):
            COM.write(chr(list[i]))
        fp.writelines("send content:")
        fp.writelines((str)(list[0:head_len]))

        print "send head:"+str(list[0:head_len])
        for j in range(data_len):
            COM.write(str(s[j]))
        print "send data:"+s
        fp.writelines(s+'\n')
        fp.close()

        send_en.delete(0, 10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0, send_data_len_cnt)

def Write_instruct_in_close_led_fun(s,send_en):
    global led_fun_open_flag
    if led_fun_open_flag == 0:
        Write_instruct(s, send_en)

def Write_instruct(s,send_en):
    global send_data_len_cnt,fp
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    i = 0
    j = 0

    if isOpened.isSet():
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        buf = s + '\n'
        data_len = len(buf)-1
        if data_len == 0:
            return
        head_len = COM_add_data_head(buf, list)

        for i in range(head_len):
            COM.write(chr(list[i]))
        print "send head:" + str(list[0:head_len])
        fp.writelines("send content:")
        fp.writelines((str)(list[0:head_len]))

        for j in range(data_len):
            COM.write(str(buf[j]))
        print "send data:" + buf
        fp.writelines(buf+'\n')
        fp.close()
        send_en.delete(0, 10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0, send_data_len_cnt)

def send_text_clear(send_txt,send_en):
    global  send_data_len_cnt

    send_txt.delete("0.0","end")
    send_data_len_cnt = 0
    send_en.delete(0, 10)

def rece_text_clear(rece_txt,rece_en):
    global  rece_data_len_cnt

    lock.acquire()
    rece_txt.delete("0.0", "end")
    rece_data_len_cnt=0
    rece_en.delete(0, 10)
    lock.release()

def COM_add_data_head(s,list):
    global crc232_flag
    head = 0
    data_len = len(s)-1

    if crc232_flag==1:
        if data_len < 126:
            cf_length = data_len | 0x80
        if (data_len > 126) & (data_len < 65535):
            cf_length = 0xFE
        if (data_len > 65535) & (data_len < 4294967295):
            cf_length = 0xFF
    else:
        if data_len < 126:
            cf_length = data_len | 0x00
        if (data_len > 126) & (data_len < 65535):
            cf_length = 0x7E
        if (data_len > 65535) & (data_len < 4294967295):
            cf_length = 0x7F

    crc_32 = binascii.crc32(s[0:data_len])
    crc_32 &= 0xffffffff

    crc_byte_low8 = 0xFF & crc_32
    crc_byte_low16 = 0xFF & (crc_32 >> 8)
    crc_byte_low24 = 0xFF & (crc_32 >> 16)
    crc_byte_low32 = 0xFF & (crc_32 >> 24)

    if  data_len < 126:
        list[2] = cf_length
        list[3] = crc_byte_low32
        list[4] = crc_byte_low24
        list[5] = crc_byte_low16
        list[6] = crc_byte_low8
        if(crc232_flag):
            head = 7
        else:
            head = 3
    if (data_len > 126) & (data_len < 65535):
        extend_len_low = data_len & 0xFF
        extend_len_high = (data_len >> 8) & 0xFF
        list[2] = cf_length
        list[3] = extend_len_high
        list[4] = extend_len_low
        list[5] = crc_byte_low32
        list[6] = crc_byte_low24
        list[7] = crc_byte_low16
        list[8] = crc_byte_low8
        if (crc232_flag):
            head = 9
        else:
            head = 5

    if (data_len > 65535) & (data_len < 4294967295):
        extend_len_low8 = data_len & 0xFF
        extend_len_low16 = (data_len >> 8) & 0xFF
        extend_len_low24 = (data_len >> 16) & 0xFF
        extend_len_low32 = (data_len >> 24) & 0xFF
        list[2] = cf_length
        list[3] = extend_len_low8
        list[4] = extend_len_low16
        list[5] = extend_len_low24
        list[6] = extend_len_low32
        list[7] = crc_byte_low32
        list[8] = crc_byte_low24
        list[9] = crc_byte_low16
        list[10] = crc_byte_low8
        if (crc232_flag):
            head = 11
        else:
            head = 7

    return head

def COMwrite_with_close_led_fun(send_txt,send_en):
    if led_fun_open_flag==0:
        COMwrite(send_txt, send_en)

def COMwrite(send_txt,send_en):
    global send_data_len_cnt
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    s = ""

    if isOpened.isSet():
        s = send_txt.get("0.0", "end")
        data_len = len(s) - 1
        if data_len == 0:
            return
        fp = open('log.txt','a+')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        head_len = COM_add_data_head(s,list)
        for i in range(head_len):
            COM.write(chr(list[i]))
        print "send head:"
        print list[0:head_len]
        fp.writelines('send content:')
        fp.writelines(str(list[0:head_len])+'\n')

        for j in range(data_len):
            COM.write(str(s[j]))
        print "send content:"
        print s[0:data_len]
        fp.writelines(s[0:data_len]+'\n')

        send_en.delete(0,10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0,send_data_len_cnt)

def COMOpen(cnv3):
    if not isOpened.isSet():
        try:
            COM.timeout = 0
            COM.xonxoff = 0
            COM.port = ComX.get()
            COM.parity = Chck.get()[0]
            COM.baudrate = int(Baud.get())
            COM.bytesize = int(Dbit.get())
            COM.stopbits = int(Sbit.get())
            COM.open()

        except Exception:
            COM.close()
            print "COM Open Error!"
        else:
            isOpened.set()
            Open.set(u"关闭")
            #cnv3.itemconfig("led",fill="green")
    else:
        isOpened.clear()
        COM.close()
        Open.set(u"打开")
        #cnv3.itemconfig("led",fill="black")


def u2art_protocols_parsing(self,rece_data,rece_len):
    parsing_data = ''
    ret_data = ''
    data = ''

    ret = rece_data.find('\xaa')
    if  ret != -1:
        data = rece_data[ret:]
        rece_len = rece_len - ret
        print 'rece_data:'+rece_data
    elif (ret == -1):
        if (rece_len != 0):
            fp = open("log.txt", 'a')
            fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
            fp.writelines('rece_content:')
            fp.writelines(rece_data+'\n')
            fp.close()
            print rece_data
            parsing_data = '数据格式错误！'
        return (parsing_data + ret_data)

    if ((rece_len >= 3) and (data[0] == '\xaa') and (data[1] == '\x55')):
        cf_len_cf = int(binascii.b2a_hex(data[2]), 16) >> 7
        cf_length_len = int(binascii.b2a_hex(data[2]), 16) & 0x7F
        if cf_len_cf:
            if ((cf_length_len < 126) and (rece_len >= 8)):
                print 'rece cf_len < 126,have crc32'
                crc_32 = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[5]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[6]), 16)
                if (rece_len >= (7 + cf_length_len)):
                    ret_data = u2art_protocols_parsing(self, data[(7 + cf_length_len):], rece_len - (7 + cf_length_len))
                    count_crc_32 = binascii.crc32(data[7:7+cf_length_len])
                    count_crc_32 &= 0xffffffff
                    if crc_32 == count_crc_32:
                        parsing_data = data[7:cf_length_len + 7]
                    else:
                        parsing_data = '数据格式错误！'
                    print 'parsing head:'+ binascii.b2a_hex(data[0:7])
                    print 'parsing data:'+ data[7:7 + cf_length_len]
                else:
                    parsing_data = '数据格式错误！'
                return (parsing_data + ret_data)

            elif ((cf_length_len == 126) and (rece_len >= 10)):
                print 'rece cf_len == 126,have crc32\n'
                data_len = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                crc_32 = (int(binascii.b2a_hex(data[5]), 16) << 8) + int(binascii.b2a_hex(data[6]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[7]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[8]), 16)
                if (rece_len >= (9 + cf_length_len)):
                    ret_data = u2art_protocols_parsing(self, data[(9 + cf_length_len):], rece_len - (9 + cf_length_len))
                    count_crc_32 = binascii.crc32(data[9:9+cf_length_len])
                    count_crc_32 &= 0xffffffff
                    if crc_32 == count_crc_32:
                        parsing_data = data[9:cf_length_len + 9]
                    else:
                        parsing_data = '数据格式错误！'
                    print 'parsing head:'+ binascii.b2a_hex(data[0:9])
                    print 'parsing data:'+ data[9:9 + cf_length_len]
                else:
                    parsing_data = '数据格式错误！'
                return (parsing_data + ret_data)

            elif ((cf_length_len == 127) and (rece_len >= 12)):
                print 'rece cf_len == 127,have crc32'
                data_len = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                data_len = (data_len << 8) + int(binascii.b2a_hex(data[5]), 16)
                data_len = (data_len << 8) + int(binascii.b2a_hex(data[6]), 16)
                crc_32 = (int(binascii.b2a_hex(data[7]), 16) << 8) + int(binascii.b2a_hex(data[8]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[9]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[10]), 16)
                if (rece_len >= (11 + cf_length_len)):
                    ret_data = u2art_protocols_parsing(self, data[(11 + cf_length_len):], rece_len - (11 + cf_length_len))
                    count_crc_32 = binascii.crc32(data[11:11+cf_length_len])
                    count_crc_32 &= 0xffffffff
                    if crc_32 == count_crc_32:
                        parsing_data = data[11:cf_length_len + 11]
                    else:
                        parsing_data = '数据格式错误！'
                    print 'parsing head:'+ binascii.b2a_hex(data[0:11])
                    print 'parsing data:'+ data[11:11 + cf_length_len]
                else:
                    parsing_data = '数据格式错误！'
                return (parsing_data + ret_data)
        else:
            if ((cf_length_len < 126) and (rece_len >= 4)):
                print 'rece cf_len < 126,no crc32'
                if(rece_len >= (3+cf_length_len)):
                    ret_data = u2art_protocols_parsing(self,data[(3+cf_length_len):],rece_len-(3+cf_length_len))
                    parsing_data = data[3:cf_length_len + 3]
                    print 'parsing head:'+ binascii.b2a_hex(data[0:3])
                    print 'parsing data:'+ data[3:3 + cf_length_len]
                else:
                    parsing_data = '数据格式错误！'
                return (parsing_data  + ret_data)

            elif ((cf_length_len == 126) and (rece_len >= 6)):
                print 'rece cf_len == 126,no crc32'
                data_len = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                if(rece_len >= (5+data_len)):
                    ret_data = u2art_protocols_parsing(self,data[(5+data_len):],rece_len-(5+data_len))
                    parsing_data = data[5:data_len + 5]
                    print 'parsing head:'+ binascii.b2a_hex(data[0:5])
                    print 'parsing data:'+ data[5:5 + cf_length_len]
                else:
                    parsing_data = '数据格式错误！'
                return (parsing_data  + ret_data)

            elif ((cf_length_len == 127) and (rece_len >= 8)):
                data_len = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                data_len = (data_len << 8) + int(binascii.b2a_hex(data[5]), 16)
                data_len = (data_len << 8) + int(binascii.b2a_hex(data[6]), 16)
                print 'rece cf_len == 127,no crc32\n'
                if(rece_len >= (7+data_len)):
                    ret_data = u2art_protocols_parsing(self,data[(7+data_len):],rece_len-(7+data_len))
                    parsing_data = data[7:data_len + 7]
                    print 'parsing head:'+ binascii.b2a_hex(data[0:7])
                    print 'parsing data:'+ data[7:7 + cf_length_len]
                else:
                    parsing_data = '数据格式错误！'
                return (parsing_data  + ret_data)

def u2art_protocols_read(self):
    global  rece_data_len_cnt
    global buf
    data = ""
    parsing_data = ''
    timeout = 0
    rece_len = 0

    while True:
        if isOpened.isSet():
            self.check_led_status()
            n = COM.inWaiting()
            if n>0:
                timeout = 0
                data += COM.read(n)
                rece_len += n
            else:
                timeout = timeout + 1
                time.sleep(0.01)
                if ((timeout > 3) and (rece_len > 3)):
                        break

    print 'rece_len:'+ str(rece_len)

    if len(data) > 0:
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        fp.writelines('rece_content:'+data+'\n')
        fp.close()

    rece_data_len_cnt = rece_data_len_cnt + rece_len - 1
    parsing_data = u2art_protocols_parsing(self,data,rece_len)
    RQueue.put(parsing_data)
    RQueue.join()

'''
def u2art_protocols_read(self):
    global  rece_data_len_cnt
    global buf
    data = ""
    timeout = 0
    rece_len = 0

    while True:
        if isOpened.isSet():
            self.check_led_status()
            n = COM.inWaiting()
            if n>0:
                timeout = 0
                data += COM.read(n)
                rece_len += n
            else:
                timeout = timeout + 1
                time.sleep(0.01)
                if ((timeout > 3) and (rece_len > 3)):
                        break

    print 'rece_len:'
    print rece_len
    print "rece_data:"
    print data
    rece_data_len_cnt = rece_data_len_cnt + rece_len - 1

    if ((rece_len >= 3) and (data[0] == '\xaa') and (data[1] == '\x55')):
        fp = open("log.txt", 'a')
        fp.writelines('['+datetime.now().strftime('%Y-%m-%d %H:%M:%S')+']')
        fp.writelines('rece_content:')
        cf_len_cf = int(binascii.b2a_hex(data[2]), 16) >> 7
        cf_length_len = int(binascii.b2a_hex(data[2]), 16) & 0x7F
        if cf_len_cf:
            if ((cf_length_len < 126) and (rece_len >= 8)):
                print 'rece cf_len < 126,have crc32\n'
                crc_32 = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[5]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[6]), 16)
                count_crc_32 = binascii.crc32(data[7:])
                count_crc_32 &= 0xffffffff
                if crc_32 == count_crc_32:
                    print binascii.b2a_hex(data[0:7])
                    print data[7:]
                    if not RQueue.full():
                        fp.writelines(binascii.b2a_hex(data[0:7]))
                        fp.writelines(data[7:] + '\n')
                        fp.close()
                        RQueue.put(data[7:])
                        RQueue.join()
                else:
                    print binascii.b2a_hex(data[0:7])
                    print data[7:]
                    if not RQueue.full():
                        fp.writelines(binascii.b2a_hex(data[0:7]))
                        fp.writelines(data[7:] + '\n')
                        fp.close()
                        RQueue.put(u'数据格式错误！！！')
                        RQueue.join()
            elif ((cf_length_len == 126) and (rece_len >= 10)):
                print 'rece cf_len == 126,have crc32\n'
                crc_32 = (int(binascii.b2a_hex(data[5]), 16) << 8) + int(binascii.b2a_hex(data[6]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[7]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[8]), 16)
                count_crc_32 = binascii.crc32(data[9:])
                count_crc_32 &= 0xffffffff
                if crc_32 == count_crc_32:
                    print binascii.b2a_hex(data[0:9])
                    print data[9:]
                    if not RQueue.full():
                        fp.writelines(binascii.b2a_hex(data[0:9]))
                        fp.writelines(data[9:] + '\n')
                        fp.close()
                        RQueue.put(data[9:])
                        RQueue.join()
                else:
                    print binascii.b2a_hex(data[0:9])
                    print data[9:]
                    fp.writelines(binascii.b2a_hex(data[0:9]))
                    fp.writelines(data[9:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(u'数据格式错误！！！')
                        RQueue.join()
            elif ((cf_length_len == 127) and (rece_len >= 12)):
                print 'rece cf_len == 127,have crc32\n'
                crc_32 = (int(binascii.b2a_hex(data[7]), 16) << 8) + int(binascii.b2a_hex(data[8]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[9]), 16)
                crc_32 = (crc_32 << 8) + int(binascii.b2a_hex(data[10]), 16)
                count_crc_32 = binascii.crc32(data[11:])
                count_crc_32 &= 0xffffffff
                if crc_32 == count_crc_32:
                    print binascii.b2a_hex(data[0:11])
                    print data[11:]
                    fp.writelines(binascii.b2a_hex(data[0:11]))
                    fp.writelines(data[11:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(data[11:])
                        RQueue.join()
                else:
                    print binascii.b2a_hex(data[0:11])
                    print data[11:]
                    fp.writelines(binascii.b2a_hex(data[0:11]))
                    fp.writelines(data[11:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(u'数据格式错误！！！')
                        RQueue.join()
        else:
            if ((cf_length_len < 126) and (rece_len >= 4)):
                print 'rece cf_len < 126,no crc32\n'
                if (rece_len - 3) == cf_length_len:
                    print binascii.b2a_hex(data[0:3])
                    print data[3:]
                    if not RQueue.full():
                        fp.writelines(binascii.b2a_hex(data[0:3]))
                        fp.writelines(data[3:] + '\n')
                        fp.close()
                        RQueue.put(data[3:rece_len])
                        RQueue.join()
                else:
                    print binascii.b2a_hex(data[0:3])
                    print data[3:]
                    fp.writelines(binascii.b2a_hex(data[0:3]))
                    fp.writelines(data[3:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(u'数据格式错误！！！')
                        RQueue.join()
            elif ((cf_length_len == 126) and (rece_len >= 6)):
                print 'rece cf_len == 126,no crc32\n'
                data_len = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                if (rece_len - 5) == data_len:
                    print binascii.b2a_hex(data[0:5])
                    print data[5:]
                    fp.writelines(binascii.b2a_hex(data[0:5]))
                    fp.writelines(data[5:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(data[5:])
                        RQueue.join()
                else:
                    print binascii.b2a_hex(data[0:5])
                    print data[5:]
                    fp.writelines(binascii.b2a_hex(data[0:5]))
                    fp.writelines(data[5:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(u'数据格式错误！！！')
                        RQueue.join()
            elif ((cf_length_len == 127) and (rece_len >= 8)):
                data_len = (int(binascii.b2a_hex(data[3]), 16) << 8) + int(binascii.b2a_hex(data[4]), 16)
                data_len = (data_len << 8) + int(binascii.b2a_hex(data[5]), 16)
                data_len = (data_len << 8) + int(binascii.b2a_hex(data[6]), 16)
                print 'rece cf_len == 127,no crc32\n'
                if (rece_len - 7) == cf_length_len:
                    print binascii.b2a_hex(data[0:7])
                    print data[7:]
                    fp.writelines(binascii.b2a_hex(data[0:7]))
                    fp.writelines(data[7:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(data[7:])
                        RQueue.join()
                else:
                    print binascii.b2a_hex(data[0:7])
                    print data[7:]
                    fp.writelines(binascii.b2a_hex(data[0:7]))
                    fp.writelines(data[7:] + '\n')
                    fp.close()
                    if not RQueue.full():
                        RQueue.put(u'数据格式错误！！！')
                        RQueue.join()
    else:
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        fp.writelines('rece_content:')
        fp.writelines(data+'\n')
        fp.close()
'''

def change_led_status(showled):
    global  led_status,led_sta

    if led_fun_open_flag == 0:
        return
    if led_status == 'green':
        led_status = 'black'
        led_sta = 'black'
        showled.itemconfig("led", fill="black")
    else:
        led_status = 'green'
        led_sta = 'green'
        showled.itemconfig("led", fill="green")

def rece_data_parsing(s,self):
    global  led_fun_open_flag,led_retrun_again
    command = ''
    seq = []
    sequen = ''

    #if led_retrun_again:
        #led_retrun_again = 0
	
    if s.find('update')>0:
        if led_fun_open_flag == 0:
            return
        led_retrun_again = 1
        index = s.find('update')
        seq = json.loads(s)
        #sequence = s[index+8:index+23]
        sequen += '\"'
        sequen += seq[1]
        sequen += '\"'

        command = '[\"respond\",'
        command += sequen
        #command += sequence
        if s.find('on')>0:
            self.showled.itemconfig("led", fill="green")
            command += ',0]'
            Write_instruct('[\"ret\",0]', self.send_en)
            Write_instruct(command, self.send_en)
        elif s.find('off')>0:
            self.showled.itemconfig("led", fill="black")
            command += ',0]'
            Write_instruct('[\"ret\",0]', self.send_en)
            Write_instruct(command, self.send_en)
        else:
            command += ',400]'
            Write_instruct('[\"ret\",0]', self.send_en)
            Write_instruct(command, self.send_en)
    if s.find('start')>0:
            command = '[\"ret\",0]'
            #Write_instruct(command, self.send_en)
    if s.find('state')>0:
            command = '[\"ret\",0]'
            Write_instruct(command, self.send_en)
    if s.find('respond')>0:
        if led_fun_open_flag == 0:
            return
        Write_instruct('[\"ret\",0]', self.send_en)

def change_led_fun_flag():
    global led_fun_open_flag,led_fun,led_fun_open_flag

    if led_fun_open_flag==0:
        led_fun.set(u'禁用')
        led_fun_open_flag = 1
    else:
        led_fun.set(u'启用')
        led_fun_open_flag = 0

def write_set_timer(self):
    command = '['
    timer_date = '[{\"id\":'
    if time_operate.get()==u'新建':
        command += "\"tmrNew\",{\"timer\":"
    else:
        command += "\"tmrEdit\",{\"timer\":"
    timer_date += time_id.get()+','
    timer_date += '\"enabled\":'
    if time_open.get()==u'开启':
        timer_date += '1,'
    else:
        timer_date += '0,'
    timer_date += '\"type\":"'
    if time_type.get()==u'单次':
        timer_date += 'once\",'
    elif time_type.get()==u'重复':
        timer_date += 'repeat\",'
    else:
        timer_date += 'duration\",'
    timer_date += '\"at\":\"'
    timer_date += time_date.get()+'\"'
    if time_do.get() != u'无':
        timer_date += ',\"do\":{\"switch\":\"'
        timer_date += time_do.get() + '\"}'
    if (time_startdo.get() != u'无') and (time_enddo.get() != u'无'):
        timer_date += ',\"startDo\":{\"switch\":\"'
        timer_date += time_startdo.get() + '\"},'
        timer_date += '\"endDo\":{\"switch\":\"'
        timer_date += time_enddo.get() + '\"}}]}]'
    else:
        timer_date += '}]}]'
    command += timer_date
    Write_instruct_in_close_led_fun(command, self.send_en)


def write_del_timer(self):
    command = '[\"tmrDel\",{\"timerID\":['
    command += time_id_array.get()
    command += ']}]'
    Write_instruct_in_close_led_fun(command, self.send_en)

def write_start_timer(self):
    command = '[\"tmrEnable\",{\"timerID\":['
    command += time_id_array.get()
    command += ']}]'
    Write_instruct_in_close_led_fun(command, self.send_en)

def write_disable_timer(self):
    command = '[\"tmrDisable\",{\"timerID\":['
    command += time_id_array.get()
    command += ']}]'
    Write_instruct_in_close_led_fun(command, self.send_en)

def check_timer_info_for_id(self):
    command = '[\"tmrQuery\",[\"timerID\",['
    command += time_id_array.get()
    command += ']]]'
    Write_instruct_in_close_led_fun(command, self.send_en)

def write_check_timer_simple(self):
    command = '[\"tmrQuery\",[\"timerInfo\"]]'
    Write_instruct_in_close_led_fun(command, self.send_en)

def subscribe_for_timer(self):
    global time_sub
    if time_sub.get() == u'订阅定时器通知':
        time_sub.set(u'取消订阅定时器通知')
        Write_instruct_in_close_led_fun('[\"tmrMsg\",1]', self.send_en)
    else:
        time_sub.set(u'订阅定时器通知')
        Write_instruct_in_close_led_fun('[\"tmrMsg\",0]', self.send_en)

def clean_all_timer(self):
    Write_instruct_in_close_led_fun('[\"tmrDelAll\"]', self.send_en)

def enable_all_timer(self):
    Write_instruct_in_close_led_fun('[\"tmrEnableAll\"]', self.send_en)

def disable_all_timer(self):
    Write_instruct_in_close_led_fun('[\"tmrDisableAll\"]', self.send_en)

def write_txt0_7_content(cnt,self):
    global txt_open_cnt
    content = {0:"",1:"",2:"",3:"",4:"",5:"",6:"",7:""}

    keep_fp = open("txt_content.txt", 'w+')

    if cnt=='0':
        Write_instruct_in_close_led_fun(txt0.get(), self.send_en)
    elif cnt=='1':
        Write_instruct_in_close_led_fun(txt1.get(), self.send_en)
    elif cnt=='2':
        Write_instruct_in_close_led_fun(txt2.get(), self.send_en)
    elif cnt=='3':
        Write_instruct_in_close_led_fun(txt3.get(), self.send_en)
    elif cnt=='4':
        Write_instruct_in_close_led_fun(txt4.get(), self.send_en)
    elif cnt=='5':
        Write_instruct_in_close_led_fun(txt5.get(), self.send_en)
    elif cnt=='6':
        Write_instruct_in_close_led_fun(txt6.get(), self.send_en)
    elif cnt=='7':
        Write_instruct_in_close_led_fun(txt7.get(), self.send_en)

    keep_fp.truncate()

    content[0] = txt0.get()
    content[1] = txt1.get()
    content[2] = txt2.get()
    content[3] = txt3.get()
    content[4] = txt4.get()
    content[5] = txt5.get()
    content[6] = txt6.get()
    content[7] = txt7.get()

    keep_fp.write(str(content))

    keep_fp.close()

def Write_set_mode(sett_mode, send_en):
    global send_data_len_cnt
    list = [0xAA, 0x55, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
    s = "[\"setting\","
    mode = sett_mode.get()
    if mode.find("1") != -1:
        mode = '1'
    elif mode.find("2") != -1:
        mode = '2'
    else:
        mode = '3'
    s += mode
    s += ']\n'

    if led_fun_open_flag != 0:
        return
    if isOpened.isSet():
        fp = open("log.txt", 'a')
        fp.writelines('[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ']')
        data_len = len(s) - 1
        if data_len == 0:
            return
        head_len = COM_add_data_head(s, list)

        for i in range(head_len):
            COM.write(chr(list[i]))
        fp.writelines("send content:")
        fp.writelines((str)(list[0:head_len]))
        for j in range(data_len):
            COM.write(str(s[j]))
        fp.writelines(s + '\n')
        fp.close()

        send_en.delete(0, 10)
        send_data_len_cnt = send_data_len_cnt + (head_len + data_len)
        send_en.insert(0, send_data_len_cnt)

class Display():
    def __init__(self):
        self.rece = Tk.Canvas(root, height=20, width=50)
        self.rece.grid(row=0, column=0, sticky="NW")
        self.rece.create_window(23, 12, window=ttk.Label(root, text=u"接收：") )

        #self.rece_txt = Tk.Text(root, height=15, width=55, border=5)
        #self.rece_txt.grid(row=1, column=0, sticky="NW")
        self.rece_txt = Tk.Text(root, height=22, width=55, border=5)
        self.rece_txt.grid(row=1, column=0, sticky="NW")

        self.cnv1 = Tk.Canvas(root, height=450, width=400)
        self.cnv1.grid(row=0, column=1, sticky="NE", rowspan=6)
        self.cnv1.create_window(102, 15, window=ttk.Button(root, text=u"tick", width=27,
                                                      command=lambda: Write_instruct_in_close_led_fun("[\"tick\"]", self.send_en)))

        self.cnv1.create_window(167, 223, window=Tk.Entry(root,width=46,textvariable=txt0))
        self.cnv1.create_window(367, 223, window=ttk.Button(root, text=u"发送", width=8,command=lambda:write_txt0_7_content('0',self)))

        self.cnv1.create_window(167, 254, window=Tk.Entry(root, width=46,textvariable=txt1))
        self.cnv1.create_window(367, 254, window=ttk.Button(root, text=u"发送", width=8,command=lambda:write_txt0_7_content('1',self)))

        self.cnv1.create_window(167, 285, window=Tk.Entry(root, width=46,textvariable=txt2))
        self.cnv1.create_window(367, 285, window=ttk.Button(root, text=u"发送", width=8,command=lambda:write_txt0_7_content('2',self)))

        self.cnv1.create_window(167, 316, window=Tk.Entry(root, width=46,textvariable=txt3))
        self.cnv1.create_window(367, 316, window=ttk.Button(root, text=u"发送", width=8,command=lambda:write_txt0_7_content('3',self)))

        self.cnv1.create_window(167, 347, window=Tk.Entry(root, width=46, textvariable=txt4))
        self.cnv1.create_window(367, 347, window=ttk.Button(root, text=u"发送", width=8,command=lambda:write_txt0_7_content('4',self)))

        self.cnv1.create_window(167, 379, window=Tk.Entry(root, width=46, textvariable=txt5))
        self.cnv1.create_window(367, 379, window=ttk.Button(root, text=u"发送", width=8,command=lambda: write_txt0_7_content('5',self)))

        self.cnv1.create_window(167, 410, window=Tk.Entry(root, width=46, textvariable=txt6))
        self.cnv1.create_window(367, 410, window=ttk.Button(root, text=u"发送", width=8,command=lambda: write_txt0_7_content('6',self)))

        self.cnv1.create_window(167, 441, window=Tk.Entry(root, width=46, textvariable=txt7))
        self.cnv1.create_window(367, 441, window=ttk.Button(root, text=u"发送", width=8,command=lambda: write_txt0_7_content('7',self)))

        self.cnv1.create_window(102, 42, window=ttk.Button(root, text=u"state", width=27,
                                                      command=lambda: Write_instruct_in_close_led_fun("[\"state\"]", self.send_en)))
        self.cnv1.create_window(102, 72, window=ttk.Button(root, text=u"rssi", width=27,
                                                      command=lambda: Write_instruct_in_close_led_fun("[\"rssi\"]", self.send_en)))
        self.cnv1.create_window(102, 102, window=ttk.Button(root, text=u"time", width=27,
                                                       command=lambda: Write_instruct_in_close_led_fun("[\"time\"]", self.send_en)))
        self.cnv1.create_window(102, 132, window=ttk.Button(root, text=u"version", width=27,
                                                       command=lambda: Write_instruct_in_close_led_fun("[\"version\"]", self.send_en)))
        self.cnv1.create_window(102, 162, window=ttk.Button(root, text=u"deviceid", width=27,
                                                       command=lambda: Write_instruct_in_close_led_fun("[\"deviceid\"]", self.send_en)))
        self.cnv1.create_window(102, 192, window=ttk.Button(root, text=u"stamac", width=27,
                                                       command=lambda: Write_instruct_in_close_led_fun("[\"stamac\"]", self.send_en)))
        self.cnv1.create_window(302, 15, window=ttk.Button(root, text=u"sapmac", width=27,
                                                            command=lambda: Write_instruct_in_close_led_fun("[\"sapmac\"]",
                                                                                           self.send_en)))
        self.cnv1.create_window(230, 42, window=ttk.Label(root, text=u"波特率："))
        self.cnv1.create_window(282, 42, window=ttk.Combobox(root, textvariable=Baud_set, values=["9600", "115200"], width=6))
        self.cnv1.create_window(358, 42, window=ttk.Button(root, text=u"baud", width=11,command=lambda: Write_set_baud_instruct(Baud_set, self.send_en)))
        self.cnv1.create_window(220, 72, window=ttk.Radiobutton(root, text=u"亮", variable=var, value=1, command=lambda:
        set_status(status)))
        self.cnv1.create_window(258, 72, window=ttk.Radiobutton(root, text=u"灭", variable=var, value=2, command=lambda:
        reset_status(status)))
        self.cnv1.create_window(341, 72, window=ttk.Button(root, text=u"sled", width=16,
                                                       command=lambda: Write_set_status_led_instruct(var, self.send_en)))
        self.cnv1.create_window(230, 102, window=ttk.Label(root, text=u"时间(s)："))
        self.cnv1.create_window(278, 102, window=ttk.Combobox(root, textvariable=dog_time, values=time_list, width=3))
        self.cnv1.create_window(351, 102, window=ttk.Button(root, text=u"dog", width=13,
                                                       command=lambda: Write_set_dogtime(dog_time, self.send_en)))
        self.cnv1.create_window(218, 132, window=ttk.Label(root, text=u"状态:"))
        self.cnv1.create_window(266, 132, window=ttk.Combobox(root, textvariable=stateInfo, values=["1:订阅", "0:退订"], width=6))
        self.cnv1.create_window(351, 132, window=ttk.Button(root, text=u"stateInfo", width=13,
                                                       command=lambda: Write_set_stateInfo(stateInfo, self.send_en)))
        self.cnv1.create_window(218, 162, window=ttk.Label(root, text=u"模式:"))
        self.cnv1.create_window(285, 162, window=ttk.Combobox(root, textvariable=sett_mode, values=["1:AP", "2:ESPTOUCH","3:退出"], width=11))
        self.cnv1.create_window(369, 162, window=ttk.Button(root, text=u"setting", width=8,
                                                       command=lambda: Write_set_mode(sett_mode, self.send_en)))

        self.cnv2 = Tk.Canvas(root, height=20, width=392)
        self.cnv2.grid(row=2, column=0, sticky="NW", columnspan=2)
        self.cnv2.create_window(23, 12, window=ttk.Label(root, text=u"发送："))

        self.send_txt = Tk.Text(root, height=8, width=43, border=5)
        self.send_txt.grid(row=4, column=0, sticky="NW", columnspan=2)
        self.send_button = Tk.Button(root, text=u"发送", width=10, height=6, command=lambda:
         COMwrite_with_close_led_fun(self.send_txt, self.send_en))
        self.send_button.grid(row=4, column=0, sticky="NW", columnspan=2,padx=315)
        #self.send = Tk.Canvas(root, height=120, width=395,bg='red')
        #self.send.grid(row=4, column=1, sticky="NW", columnspan=2)
        #self.send.create_window(355, 62, window=Tk.Button(root, text=u"发送",width=10,height=6,command=lambda:
        #COMwrite_with_close_led_fun(self.send_txt, self.send_en)))

        self.time = Tk.Canvas(root, height=130, width=600)
        self.time.grid(row=8, column=0, sticky="NW", columnspan=2)

        self.time.create_window(42, 15, window=ttk.Label(root, text=u"定时器类型："))
        self.time.create_window(111, 15, window=ttk.Combobox(root, textvariable=time_type, values=[u'单次',u'重复',u'循环'], width=6))
        self.time.create_window(320, 15, window=ttk.Label(root, text=u"定时器ID数组:"))
        self.time.create_window(396, 15, window=Tk.Entry(root, width=10, textvariable=time_id_array))
        self.time.create_window(515, 15, window=ttk.Button(root, textvariable=time_sub, width=21,command=lambda: subscribe_for_timer(self)))

        self.time.create_window(36, 40, window=ttk.Label(root, text=u"定时器ID："))
        self.time.create_window(106, 40, window=Tk.Entry(root, width=10, textvariable=time_id))
        self.time.create_window(355, 41, window=ttk.Button(root, text=u"删除定时器组", width=21,command=lambda:write_del_timer(self)))
        self.time.create_window(515, 41, window=ttk.Button(root, text=u"查询定时器简报", width=21,command=lambda: write_check_timer_simple(self)))

        self.time.create_window(36, 65, window=ttk.Label(root, text=u"是否启用："))
        self.time.create_window(103, 65, window=ttk.Combobox(root, textvariable=time_open, values=[u'开启', u'关闭'],width=8))
        self.time.create_window(355, 67, window=ttk.Button(root, text=u"启用定时器组", width=21,command=lambda: write_start_timer(self)))
        self.time.create_window(515, 67, window=ttk.Button(root, text=u"删除所有定时器", width=21,command=lambda: clean_all_timer(self)))

        self.time.create_window(36, 90, window=ttk.Label(root, text=u"定时时间："))
        self.time.create_window(165, 90, window=Tk.Entry(root, width=28, textvariable=time_date))
        self.time.create_window(355, 93, window=ttk.Button(root, text=u"禁用定时器组", width=21,command=lambda: write_disable_timer(self)))
        self.time.create_window(515, 93, window=ttk.Button(root, text=u"启用所有定时器", width=21,command=lambda: enable_all_timer(self)))

        self.time.create_window(170, 15, window=ttk.Label(root, text=u"Do："))
        self.time.create_window(226, 15, window=ttk.Combobox(root, textvariable=time_do, values=['off','on',u'无'], width=8))


        self.time.create_window(184, 40, window=ttk.Label(root, text=u"StartDo："))
        self.time.create_window(236, 40, window=ttk.Combobox(root, textvariable=time_startdo, values=['off', 'on','无'], width=5))

        self.time.create_window(180, 65, window=ttk.Label(root, text=u"EndDo："))
        self.time.create_window(236, 65, window=ttk.Combobox(root, textvariable=time_enddo, values=['off', 'on','无'], width=5))

        self.time.create_window(42, 115, window=ttk.Label(root, text=u"定时器操作："))
        self.time.create_window(130, 115, window=ttk.Combobox(root, textvariable=time_operate, values=[u'新建', u'编辑'],width=12))
        self.time.create_window(225, 115, window=ttk.Button(root, text=u"发送", width=10,command=lambda:write_set_timer(self)))
        self.time.create_window(355, 119, window=ttk.Button(root, text=u"查询定时器组", width=21,command=lambda: check_timer_info_for_id(self)))
        self.time.create_window(515, 119, window=ttk.Button(root, text=u"禁用所有定时器", width=21,command=lambda: disable_all_timer(self)))

        self.showled = Tk.Canvas(root, height=125, width=190)
        self.showled.grid(row=7, column=1, sticky="SE", rowspan=2, padx=5)
        self.showled.create_oval(146, 80, 186, 120, fill="black", tag='led')
        self.showled.create_window(90, 100, window=Tk.Button(root, text=u"模拟控制按键", width=13, height=2,command=lambda: change_led_status(self.showled)))
        self.showled.create_window(20, 100, window=Tk.Button(root, textvariable=led_fun, width=3, height=2,command=lambda: change_led_fun_flag()))

        self.cnv3 = Tk.Canvas(root, height=26, width=600)
        self.cnv3.grid(row=5, column=0, sticky="NW", columnspan=2)
        self.cnv3.create_window(30, 15, window=ttk.Label(root, text=u"串口号  "))
        self.cnv3.create_window(105, 15, window=ttk.Combobox(root, textvariable=ComX, values=port_list, width=12))
        self.cnv3.create_window(202, 15, window=ttk.Label(root, text=u"波特率  "))
        self.cnv3.create_window(277, 15,window=ttk.Combobox(root, textvariable=Baud, values=["9600", "115200"], width=12))
        #self.cnv3.create_window(382, 15, window=ttk.Button(root, text=u"发送", width=9, command=lambda:
        #COMwrite_with_close_led_fun(self.send_txt, self.send_en)))
        self.cnv3.create_window(470, 15, window=ttk.Button(root, textvariable=Open, width=35,command=lambda: COMOpen(self.cnv3)))

        self.cnv5 = Tk.Canvas(root, height=26, width=600)
        self.cnv5.grid(row=6, column=0, sticky="SW",columnspan=2)
        self.cnv5.create_window(370, 15, window=ttk.Checkbutton(root, text=u"使用CRC32校验", variable=HexD, width=14,
                                                          command=lambda: change_crc32()))
        self.cnv5.create_window(480, 15, window=ttk.Button(root, text=u"清除接收", width=9, command=lambda:
        rece_text_clear(self.rece_txt, self.rece_en)))
        self.cnv5.create_window(560, 15, window=ttk.Button(root, text=u"清除发送", width=9, command=lambda:
         send_text_clear(self.send_txt, self.send_en)))

        self.send_cnt = Tk.Label(root, text=u'发送长度 ')
        self.send_cnt.grid(row=6, column=0, sticky="W", columnspan=2, padx=3)
        self.send_en = Tk.Entry(root, width=12)
        self.send_en.grid(row=6, column=0, sticky="W", columnspan=2, padx=56)

        self.rece_cnt = Tk.Label(root, text=u'接收长度 ')
        self.rece_cnt.grid(row=6, column=0, sticky="W", columnspan=2, padx=154)
        self.rece_en = Tk.Entry(root, width=12)
        self.rece_en.grid(row=6, column=0, sticky="W", columnspan=2, padx=207)

        self.time = Tk.Canvas(root, height=5, width=795,bg='white')
        self.time.grid(row=7, column=0, sticky="NW", columnspan=2)

    def check_led_status(self):
        global led_status,led_status_read_cnt,led_status_old,led_sta
        command = "[\"update\",0,{\"switch\":\""

        if led_status_read_cnt<10:
            led_status_read_cnt += 1
        else:
            led_status_read_cnt = 0
            if (led_status_old==led_sta):
                return
            else:
                led_status_old = led_sta
                if led_sta == 'black':
                    command += 'off'
                else:
                    command += 'on'
                command += "\"}]"
                print command
                Write_instruct(command,self.send_en)

    def COMTrue(self):
        try:
            while True:
                u2art_protocols_read(self)
        except Exception:
            print sys.exc_info()[0], sys.exc_info()[1]

    def COMshow(self):
        s = ''
        see_cnt = 1
        while True:
            if isOpened.isSet():
                try:
                    s = RQueue.get()
                    self.rece_txt.mark_set('insert', 'end')
                    if len(s) > 0:
                        #self.rece_txt.config(state='normal')
                        self.rece_txt.insert("insert", s)
                        self.rece_txt.insert("insert", '\n')
                        self.rece_en.delete(0,10)
                        self.rece_en.insert("insert", rece_data_len_cnt)
                        self.rece_txt.see('insert')
                        #self.rece_txt.config(state='disable')
                    rece_data_parsing(s, self)
                    s = ''
                    RQueue.task_done()
                    print
                except Exception:
                    print sys.exc_info()[0], sys.exc_info()[1]


def read_start_init():
    global txt0,txt1,txt2,txt3,txt4,txt5,txt6,txt7
    s = ''

    keep_fp = open("txt_content.txt",'a+')
    s = keep_fp.read()
    cnt_1 = s.find('0:')
    cnt_2 = s.find('1:')
    txt0.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('1:')
    cnt_2 = s.find('2:')
    txt1.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('2:')
    cnt_2 = s.find('3:')
    txt2.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('3:')
    cnt_2 = s.find('4:')
    txt3.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('4:')
    cnt_2 = s.find('5:')
    txt4.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('5:')
    cnt_2 = s.find('6:')
    txt5.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('6:')
    cnt_2 = s.find('7:')
    txt6.set(s[(cnt_1+4):(cnt_2-3)])

    cnt_1 = s.find('7:')
    cnt_2 = s.find('}:')
    txt7.set(s[(cnt_1+4):(cnt_2-1)])

    keep_fp.close()

if __name__ == "__main__":
    root.title("TC调试助手v0.2.2")
    root.iconbitmap("bitbug_favicon.ico")
    root.resizable(False, False)
    read_start_init()
    D = Display()

    my_thread = threading.Thread(target=D.COMTrue)
    my_thread.setDaemon(True)
    my_thread.start()

    show_thread = threading.Thread(target=D.COMshow)
    show_thread.setDaemon(True)
    show_thread.start()

    #parsing_thread = threading.Thread(target=D.COMparsing)
    #parsing_thread.setDaemon(True)
    #parsing_thread.start()

    root.mainloop()







